package com.vil.controller;

import com.vil.common.Constants;
import com.vil.entity.Admin;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


//基本Controller 获取当前登录用户|日期国际化转换
public class BaseController {
	
	private Admin currentAdmin;

	public void setCurrentAdmin(Admin currentAdmin) {
		this.currentAdmin = currentAdmin;
	}

	public Admin getCurrentAdmin() {
		if (null == this.currentAdmin) {
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			HttpSession session = request.getSession(false);
			if (null != session) {
				currentAdmin = (Admin) session.getAttribute(Constants.USER_SESSION);
			} else {
				currentAdmin = null;
			}
		}
		return currentAdmin;
	}

	//判断session中管理员是否为空
	public boolean isNull(){
		if (currentAdmin!=null){
			System.out.println("buweiksds");
			return true;
		}
		return false;
	}

	//判断用户状态是否为启用状态  若不是 则不能进行业务操作 如修改、删除、增加
	public boolean isActive(){
		if (currentAdmin.getStatus()==1){
			return true;
		}
		return false;
	}
	
	//日期国际化 转换
	@InitBinder
	public void InitBinder(WebDataBinder dataBinder){
		dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		    public void setAsText(String value) {
		        try {
		            setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
		        } catch(ParseException e) {
		            setValue(null);
		        }
		    }
		    public String getAsText() {
		        return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
		    }        
		});
	}

}
